#!/usr/bin/env python
import os, sys
import glob
import fnmatch
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import matplotlib.dates as mdate
import datetime
from astropy.io import fits

def getFitsList(dirname):
    pattern = '*.fits'
    flist = []
    for root, dirs, files in os.walk(dirname):
        matches = fnmatch.filter(files, pattern)
        for m in matches:
            flist.append('{}/{}'.format(root,m))
    flist = np.unique(flist)

    if len(flist) == 0:
        raise Exeption('==> length of flist[] is zero.')

    return flist

def readDateTemp(dirname):
    flist = getFitsList(dirname)
    date, temp = [], []
    for i in range(len(flist)):
        f = fits.open(flist[i])
        d = f[0].header['DATE'].replace('-','/')
        print('### {}'.format(d))
        date.append(d)
        temp.append(f[0].header['SYSTEMP'])

    return date, temp

def plotDateTemp(date, temp):
    timestamp = pd.to_datetime(date)
    fig = plt.figure(figsize=(15,6))
    ax = plt.subplot(111)
    ax.xaxis.set_major_formatter(mdate.DateFormatter('%m-%d %H:%M'))
    plt.xticks(pd.date_range(timestamp[0], timestamp[-1], freq='10min'), rotation=30)
    ax.plot(timestamp, temp, 'o')
    ax.set_xlabel('Dates')
    ax.set_ylabel('Temp (K)')
    ax.grid(ls='dashed')
    plt.tight_layout()
    plt.show()

if __name__ == '__main__':
    if len(sys.argv) != 2:
        raise Exception('##> a dirname is needed')
    date, temp = readDateTemp(sys.argv[1])
    plotDateTemp(date, temp)

